<template>
  <div class="ranking-list">
    <!-- 排行榜表格 -->
    <div class="table-container">
      <n-data-table
        :columns="columns"
        :data="tableData"
        :loading="loading"
        :pagination="paginationConfig"
        :row-key="(row: any) => row.id"
        :scroll-x="1200"
        size="small"
        striped
        :row-props="rowProps"
        @update:page="handlePageChange"
        @update:page-size="handlePageSizeChange"
        @update:sorter="handleSorterChange"
      />
    </div>

    <!-- 空状态 -->
    <div v-if="!items.length && !loading" class="empty-state">
      <n-empty description="暂无数据">
        <template #icon>
          <n-icon :size="48" :depth="3">
            <BusinessOutline />
          </n-icon>
        </template>
      </n-empty>
    </div>
  </div>
</template>

<script setup lang="ts">
import { computed, h, ref, onMounted, onUnmounted } from 'vue'
import { NDataTable, NEmpty, NIcon, NImage } from 'naive-ui'
import { BusinessOutline } from '@vicons/ionicons5'
import type { SpecialOperationItem, MaterialInfo } from '@/types/specialOperation'
import type { DataTableColumns } from 'naive-ui'
import MaterialsList from './MaterialsList.vue'

// Props
const props = defineProps<{
  items: SpecialOperationItem[]
  total: number
  currentPage: number
  pageSize: number
  loading?: boolean
  materialInfos?: Record<string, MaterialInfo>
}>()

// Emits
const emit = defineEmits<{
  'page-change': [page: number]
  'page-size-change': [pageSize: number]
  'item-click': [item: SpecialOperationItem]
  'sort-change': [sortInfo: { key: string, order: 'ascend' | 'descend' | false }]
}>()

// 响应式状态
const isMobile = ref(false)

// 检测移动端
const checkMobile = () => {
  isMobile.value = window.innerWidth <= 768
}

// 生命周期
onMounted(() => {
  checkMobile()
  window.addEventListener('resize', checkMobile)
})

onUnmounted(() => {
  window.removeEventListener('resize', checkMobile)
})

// 表格数据
const tableData = computed(() => {
  return props.items.map((item, index) => ({
    ...item,
    rank: (props.currentPage - 1) * props.pageSize + index + 1
  }))
})

// 表格列配置
const columns = computed<DataTableColumns<SpecialOperationItem & { rank: number }>>(() => [
  {
    title: '排名',
    key: 'rank',
    width: 70,
    minWidth: 70,
    align: 'center',
    render: (row) => {
      const rankClass = row.rank <= 3 ? `rank-${row.rank}` : 'rank-normal'
      return h('span', { class: `rank-badge ${rankClass}` }, row.rank)
    }
  },
  {
    title: '物品',
    key: 'name',
    width: 180,
    minWidth: 150,
    render: (row) => {
      return h('div', { class: 'item-info' }, [
        h('div', { class: `item-image-wrapper grade-border-${row.grade || 1}` }, [
          h(NImage, {
            src: row.image || '/images/default-item.png',
            width: 24,
            height: 24,
            class: 'item-image',
            fallbackSrc: '/images/default-item.png'
          }),
          h('div', {
            class: `grade-indicator grade-${row.grade || 1}`
          }, `${row.grade || 1}`)
        ]),
        h('div', { class: 'item-details' }, [
          h('div', { class: 'item-name' }, row.name),
        ])
      ])
    }
  },
  {
    title: '售价',
    key: 'sale_price',
    width: 90,
    minWidth: 80,
    align: 'right',
    sorter: true,
    render: (row) => h('span', { class: 'price-text' }, row.sale_price?.toLocaleString() || '-')
  },
  {
    title: '成本',
    key: 'cost_price',
    width: 90,
    minWidth: 80,
    align: 'right',
    sorter: true,
    render: (row) => h('span', { class: 'cost-text' }, row.cost_price?.toLocaleString() || '-')
  },
  {
    title: '手续费',
    key: 'fee',
    width: 90,
    minWidth: 80,
    align: 'right',
    sorter: true,
    render: (row) => h('span', { class: 'fee-text' }, row.fee?.toLocaleString() || '-')
  },
  {
    title: '保证金',
    key: 'bail',
    width: 90,
    minWidth: 80,
    align: 'right',
    sorter: true,
    render: (row) => h('span', { class: 'deposit-text' }, row.bail?.toLocaleString() || '-')
  },
  {
    title: '净利润',
    key: 'lirun',
    width: 100,
    minWidth: 90,
    align: 'right',
    sorter: true,
    render: (row) => {
      const profit = row.lirun || 0
      const profitClass = profit > 0 ? 'profit-positive' : profit < 0 ? 'profit-negative' : 'profit-zero'
      return h('span', { class: `profit-text ${profitClass}` }, profit.toLocaleString())
    }
  },
  {
    title: '生产周期',
    key: 'period',
    width: 90,
    minWidth: 80,
    align: 'center',
    sorter: true,
    render: (row) => h('span', {}, `${row.period || 0}小时`)
  },
  {
    title: '生产数量',
    key: 'per_count',
    width: 90,
    minWidth: 80,
    align: 'center',
    sorter: true,
    render: (row) => h('span', {}, row.per_count || 0)
  },
  {
    title: '每小时利润',
    key: 'profit_per_hour',
    width: 110,
    minWidth: 100,
    align: 'right',
    sorter: true,
    render: (row) => {
      const hourlyProfit = row.profit_per_hour || 0
      const profitClass = hourlyProfit > 0 ? 'profit-positive' : hourlyProfit < 0 ? 'profit-negative' : 'profit-zero'
      return h('span', { class: `profit-text ${profitClass}` }, hourlyProfit.toLocaleString())
    }
  },
  {
    title: '所需材料',
    key: 'materials',
    width: 220,
    minWidth: 180,
    align: 'center',
    render: (row) => {
      return h(MaterialsList, {
        materials: row.materials || '',
        materialInfos: props.materialInfos || {}
      })
    }
  }
])

// 分页配置
const paginationConfig = computed(() => ({
  page: props.currentPage,
  pageSize: props.pageSize,
  itemCount: props.total,
  showSizePicker: !isMobile.value,
  pageSizes: [10, 20, 50, 100],
  showQuickJumper: !isMobile.value,
  prefix: (info: { startIndex: number; endIndex: number; page: number; pageSize: number; pageCount: number; itemCount: number | undefined }) => `共 ${info.itemCount || 0} 条记录`
}))

// 处理页码变化
const handlePageChange = (page: number) => {
  emit('page-change', page)
}

// 处理页面大小变化
const handlePageSizeChange = (size: number) => {
  emit('page-size-change', size)
}

// 处理物品点击（保留以防其他地方需要）
const handleItemClick = (item: SpecialOperationItem) => {
  emit('item-click', item)
}

// 处理排序变化
const handleSorterChange = (sorter: any) => {
  if (!sorter) {
    emit('sort-change', { key: '', order: false })
    return
  }

  let key = ''
  let order: 'ascend' | 'descend' | false = false

  if (Array.isArray(sorter)) {
    // 多列排序，取第一个
    const firstSorter = sorter[0]
    if (firstSorter) {
      key = firstSorter.columnKey
      order = firstSorter.order
    }
  } else {
    // 单列排序
    key = sorter.columnKey
    order = sorter.order
  }

  emit('sort-change', { key, order })
}

// 行属性配置 - 添加点击事件
const rowProps = (row: SpecialOperationItem & { rank: number }) => {
  return {
    style: 'cursor: pointer;',
    onClick: () => {
      emit('item-click', row)
    }
  }
}
</script>

<style scoped>
.ranking-list {
  display: flex;
  flex-direction: column;
  gap: 20px;
}

.table-container {
  flex: 1;
  background: var(--n-color);
  border-radius: 8px;
  overflow: hidden;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.empty-state {
  display: flex;
  align-items: center;
  justify-content: center;
  min-height: 200px;
}

/* 排名徽章样式 */
:deep(.rank-badge) {
  display: inline-flex;
  align-items: center;
  justify-content: center;
  width: 20px;
  height: 20px;
  border-radius: 50%;
  font-weight: bold;
  font-size: 11px;
}

:deep(.rank-1) {
  background: linear-gradient(135deg, #ffd700, #ffed4e);
  color: #b45309;
  box-shadow: 0 2px 4px rgba(255, 215, 0, 0.3);
}

:deep(.rank-2) {
  background: linear-gradient(135deg, #c0c0c0, #e5e7eb);
  color: #374151;
  box-shadow: 0 2px 4px rgba(192, 192, 192, 0.3);
}

:deep(.rank-3) {
  background: linear-gradient(135deg, #cd7f32, #d97706);
  color: white;
  box-shadow: 0 2px 4px rgba(205, 127, 50, 0.3);
}

:deep(.rank-normal) {
  background: var(--n-color-target);
  color: var(--n-text-color-disabled);
}

/* 物品信息样式 */
:deep(.item-info) {
  display: flex;
  align-items: center;
  gap: 12px;
  line-height: 1;
}

:deep(.item-image-wrapper) {
  position: relative;
  border-radius: 8px;
  padding: 2px;
  background: linear-gradient(135deg, var(--grade-color), var(--grade-color-light));
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
  transition: all 0.3s ease;
  display: inline-block;
  vertical-align: top;
  line-height: 0;
  width: 28px;
  height: 28px;
  flex-shrink: 0;
}

:deep(.n-data-table-tr:hover .item-image-wrapper) {
  transform: scale(1.05);
  box-shadow: 0 4px 8px rgba(0, 0, 0, 0.2);
}

:deep(.item-image) {
  border-radius: 6px;
  display: block;
  vertical-align: top;
  line-height: 0;
}

/* 修复NImage组件的额外空间 */
:deep(.item-image .n-image) {
  display: block;
  line-height: 0;
}

:deep(.item-image .n-image img) {
  display: block;
  vertical-align: top;
}

:deep(.grade-indicator) {
  position: absolute;
  top: -2px;
  right: -2px;
  width: 10px;
  height: 10px;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 7px;
  font-weight: bold;
  color: white;
  text-shadow: 0 1px 2px rgba(0, 0, 0, 0.5);
}

:deep(.item-details) {
  display: flex;
  flex-direction: column;
  gap: 2px;
}

:deep(.item-name) {
  font-weight: 500;
  color: var(--n-text-color);
  font-size: 14px;
}

:deep(.item-category) {
  font-size: 12px;
  color: var(--n-text-color-disabled);
}

/* 等级边框颜色 */
:deep(.grade-border-1) {
  --grade-color: #909399;
  --grade-color-light: #c0c4cc;
}

:deep(.grade-border-2) {
  --grade-color: #67c23a;
  --grade-color-light: #95d475;
}

:deep(.grade-border-3) {
  --grade-color: #409eff;
  --grade-color-light: #79bbff;
}

:deep(.grade-border-4) {
  --grade-color: #9c27b0;
  --grade-color-light: #ba68c8;
}

:deep(.grade-border-5) {
  --grade-color: #e6a23c;
  --grade-color-light: #f0c78a;
}

:deep(.grade-border-6) {
  --grade-color: #f56c6c;
  --grade-color-light: #f89898;
}

/* 等级指示器颜色 */
:deep(.grade-1) {
  background: #909399;
}

:deep(.grade-2) {
  background: #67c23a;
}

:deep(.grade-3) {
  background: #409eff;
}

:deep(.grade-4) {
  background: #9c27b0;
}

:deep(.grade-5) {
  background: #e6a23c;
}

:deep(.grade-6) {
  background: #f56c6c;
}

/* 价格和利润样式 */
:deep(.price-text) {
  font-weight: 500;
  color: var(--n-text-color);
}

:deep(.cost-text) {
  color: var(--n-error-color);
}

:deep(.fee-text) {
  color: var(--n-warning-color);
}

:deep(.deposit-text) {
  color: var(--n-info-color);
}

:deep(.profit-positive) {
  color: var(--n-success-color);
  font-weight: 600;
}

:deep(.profit-negative) {
  color: var(--n-error-color);
  font-weight: 600;
}

:deep(.profit-zero) {
  color: var(--n-text-color-disabled);
}



/* 表格样式优化 */
:deep(.n-data-table) {
  --n-th-padding: 1px 16px;
  --n-td-padding: 1px 16px;
}

:deep(.n-data-table-th) {
  background: var(--n-table-header-color);
  font-weight: 600;
  color: var(--n-text-color);
  border-bottom: 2px solid var(--n-border-color);
}

:deep(.n-data-table-td) {
  border-bottom: 1px solid var(--n-border-color);
  vertical-align: middle;
}

:deep(.n-data-table-tr:hover .n-data-table-td) {
  background: var(--n-color-hover);
}

/* 移动端适配 */
@media (max-width: 768px) {
  .ranking-list {
    gap: 16px;
  }

  .table-container {
    border-radius: 6px;
    margin: 0 -16px;
  }

  :deep(.n-data-table) {
    --n-th-padding: 1px 8px;
    --n-td-padding: 1px 8px;
    font-size: 12px;
  }

  :deep(.item-name) {
    font-size: 12px;
    line-height: 1.3;
  }

  :deep(.item-category) {
    font-size: 10px;
  }

  :deep(.rank-badge) {
    width: 18px;
    height: 18px;
    font-size: 9px;
  }

  :deep(.item-image-wrapper) {
    width: 24px;
    height: 24px;
  }

  :deep(.grade-indicator) {
    width: 8px;
    height: 8px;
    font-size: 6px;
  }

  :deep(.price-text),
  :deep(.cost-text),
  :deep(.fee-text),
  :deep(.deposit-text),
  :deep(.profit-text) {
    font-size: 12px;
  }
}

/* 平板端适配 */
@media (max-width: 1024px) and (min-width: 769px) {
  :deep(.n-data-table) {
    --n-th-padding: 1px 12px;
    --n-td-padding: 1px 12px;
  }

  :deep(.item-name) {
    font-size: 13px;
  }

  :deep(.item-category) {
    font-size: 11px;
  }
}
</style>
